package com.newly.center.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.newly.api.business.feign.VehicleClient;
import com.newly.center.business.service.VehicleService;
import com.newly.common.base.annotation.NewlyLog;
import com.newly.common.base.constants.CodeConstant;
import com.newly.common.base.constants.MenuConstant;
import com.newly.common.base.constants.ServerUriConstant;
import com.newly.common.base.entity.R;
import com.newly.common.base.entity.auth.ICurrentTenant;
import com.newly.common.base.entity.business.Dto.CarDto;
import com.newly.common.base.entity.business.Dto.CarListDto;
import com.newly.common.base.entity.business.Po.Vehicle;
import com.newly.common.base.entity.business.Vo.ExcelVehicle;
import com.newly.common.base.exception.NewlyException;
import com.newly.common.core.utils.ExcelUtil;
import com.newly.common.core.utils.NewlyCommonUtils;
import com.newly.common.core.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @anthor sbq
 * @date 2021/10/26 17:37
 */
@RestController
@RequestMapping(ServerUriConstant.NEWLY_BUSINESS_CAR)
public class VehicleController implements VehicleClient {

    @Autowired
    VehicleService vehicleService;

    private  String str;

    @Autowired
    private RequestUtils requestUtils;

    @Override
    public void getTemplate(HttpServletResponse response) {
        ExcelUtil.getTemplate(response, "车辆信息导入模版.xlsx");
    }

    @NewlyLog(ability = MenuConstant.Ability.EXP, title = "车辆", isOpen = false)
    @Override
    public void export(HttpServletResponse response, CarListDto carListDto) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        carListDto.setPageSize(1);
        int totalCount = vehicleService.getPage(currentTenant, carListDto).getTotalCount();
        if (totalCount < 1) {
            throw new NewlyException(CodeConstant.FAILED, "无车辆信息数据");
        }
        carListDto.setPageSize(totalCount);
        List<Vehicle> list = (List<Vehicle>) vehicleService.getPage(currentTenant, carListDto).getList();

        List<ExcelVehicle> collect = list.stream().map(v -> {
            ExcelVehicle excel = BeanUtil.copyProperties(v, ExcelVehicle.class, "state", "blackName");
            Integer state = v.getState();
            Integer blackName = v.getBlackName();
            excel.setState(state == null ? "" : (state == 0 ? "正常" : "异常"));
            excel.setBlackName(blackName == null ? "" : (blackName == 1 ? "是" : "否"));
            return excel;
        }).collect(Collectors.toList());

        ExcelUtil.export(response, "车辆信息表", null, collect, ExcelVehicle.class);
    }

    @NewlyLog(ability = MenuConstant.Ability.IMP, title = "车辆", isOpen = false)
    @Override
    public R importVehicle(MultipartFile file) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        List<ExcelVehicle> list = ExcelUtil.importExcel(file, ExcelVehicle.class, null);
        if (ObjectUtil.isEmpty(list)) {
            throw new NewlyException(CodeConstant.FAILED, "表格无数据");
        }
        List<String> excelVehicleNumbers = list.stream().map(ExcelVehicle::getVehicleNumber)
                .filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());

        List<String> collect = NewlyCommonUtils.getListRepeat(excelVehicleNumbers);
        if (collect.size() > 0) {
            return R.fail(CodeConstant.FAILED, collect, "excel表中有重复车牌号");
        }

        List<String> vehicleNumbers = vehicleService.list(
                Wrappers.lambdaQuery(Vehicle.class)
                        .select(Vehicle::getVehicleNumber).eq(Vehicle::getIsDeleted, 0)
        ).stream().map(Vehicle::getVehicleNumber).collect(Collectors.toList());

        excelVehicleNumbers.retainAll(vehicleNumbers);
        if (excelVehicleNumbers.size() > 0) {
            return R.fail(CodeConstant.FAILED, excelVehicleNumbers, "以下车牌号库中已存在");
        }

        boolean b = vehicleService.batchSave(list, currentTenant);
        return b ? R.ok() : R.fail("导入车辆信息失败");
    }

    @NewlyLog(ability = MenuConstant.Ability.QUE, title = "车辆", isOpen = false)
    @Override
    public R getPage(CarListDto carListDto) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        return R.ok(vehicleService.getPage(currentTenant, carListDto));
    }

    @Override
    public R getListByCarNumber(String carNumber, Integer offset) {

        if (StringUtils.isBlank(carNumber))
            return R.fail("车牌号不能为空");
        return R.ok(vehicleService.getCarDetails(carNumber, offset));
    }

    @NewlyLog(ability = MenuConstant.Ability.UPD, title = "车辆", isOpen = true)
    @Override
    public R edit(CarDto carDto) {
        if (carDto.getId() == null)
            return R.fail("车辆id不能为空");
        this.vehicleService.edit(carDto);
        return R.ok();
    }

    @NewlyLog(ability = MenuConstant.Ability.ADD, title = "车辆", isOpen = true)
    @Override
    public R save(CarDto carDto) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        this.vehicleService.save(carDto, currentTenant);
        return R.ok();
    }

    @NewlyLog(ability = MenuConstant.Ability.DEL, title = "车辆", isOpen = true)
    @Override
    public R delete(Long[] ids) {
        if (ids.length == 0)
            return R.fail("id不能为空");
        return this.vehicleService.delete(ids);
    }

    @Override
    public R repeat(String carNumber) {
        if (StringUtils.isBlank(carNumber))
            return R.fail("参数车牌号不能为空！");
        return this.vehicleService.repeat(carNumber) ? R.fail(1, "车牌号已存在") : R.ok();
    }


    @Override
    public R setBlackName(String id, String carNumber, Boolean isBlackName) {
        if (StringUtils.isBlank(carNumber))
            return R.fail("参数车牌号不能为空！");
        return this.vehicleService.setBlackName(id, carNumber, isBlackName) ? R.ok() : R.fail(1, "设置失败");
    }
}
